package persistance.database.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import persistance.hibernate.InitSessionFactory;
import domain.valueObejcts.Employee;

public class EmployeeDAO {

	private static Session session;

	public static Employee create(Employee emp) {
		session = InitSessionFactory.getInstance().getCurrentSession();
		Transaction tx = session.beginTransaction();
		session.save(emp);
		tx.commit();
		return emp;
	}

	@SuppressWarnings("unchecked")
	public static List<Employee> read(HashMap<String, String> filter) {
		List<Employee> result = new ArrayList<Employee>();
		List<String> list = new ArrayList<String>();
		
		for (Map.Entry<String, String> entry : filter.entrySet()){
			String column = entry.getKey();
			if(column.equals("forName") || column.equals("surName")){
				list.add(column + " LIKE CONCAT('%', :" + column + ", '%')");
			} else {
				list.add(column + " = :" + column);
			}
		}
		
		StringBuilder sb = new StringBuilder();
		if(filter.size() > 0){
			sb.append("WHERE ");
			sb.append(list.remove(0));
			for (String s : list) {
				sb.append(" AND ");
				sb.append(s);
			}
		}
		
		session = InitSessionFactory.getInstance().getCurrentSession();
		Transaction tx = session.beginTransaction();
		Query query = session.createQuery("FROM Employee " + sb.toString());
		
		for (Map.Entry<String, String> entry : filter.entrySet()){
			String column = entry.getKey();
			String value = entry.getValue();
			if(column.equals("type") || column.equals("workCondition") || column.equals("id")){
				query.setParameter(column, Integer.parseInt(value));
			} else {
				query.setParameter(column, value);
			}
		}
		
		result = query.list();
		tx.commit();
		filter.clear();
		
		return result;
	}
	
	public static Employee update(Employee emp) {
		session = InitSessionFactory.getInstance().getCurrentSession();
		Transaction tx = session.beginTransaction();
		session.update(emp);
		tx.commit();
		return emp;
	}

}
